package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * 类描述：
 */
@Api(tags = "用户管理相关接口")
@RequestMapping("/user/user")
@RestController
public class UserController {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;

    @ApiOperation("用户微信小程序登录")
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        //调用登录接口
        User user=userService.login(userLoginDTO);

        //封装给前端的数据UserLoginVO
        UserLoginVO userLoginVO=new UserLoginVO();
        //补全属性，ID，Openid
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(user.getOpenid());
        //补全属性，token（通过jwt工具类生成）
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        claims.put("openid",user.getOpenid());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        userLoginVO.setToken(token);

        return Result.success(userLoginVO);
    }
}
